package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.ApCollectionService;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author itusian
 */
@Slf4j
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private BehaviorFeign apBehaviorEntryService;


    @Override
    public ResponseResult apCollection(CollectionBehaviorDto dto) {
        //1.检查参数
        if(dto == null || dto.getEntryId() == null || (dto.getType() < 0 && dto.getType() > 2)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEntryId(
                user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //3.点赞或取消点赞
        ApCollection apLikesBehavior = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getEntryId()).eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if(apLikesBehavior == null && dto.getType() == 0){
            apLikesBehavior = new ApCollection();
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setArticleId(dto.getEntryId());
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());
            apLikesBehavior.setCollectionTime(new Date());
            save(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
